<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-box">
        <text class="iconfont icon-segi-icon-search"></text>
        <input 
          type="text" 
          v-model="searchKey" 
          placeholder="搜索网站" 
          confirm-type="search"
          @confirm="handleSearch"
        />
        <text 
          class="clear-btn" 
          v-if="searchKey"
          @tap="clearSearch"
        >×</text>
      </view>
    </view>

    <!-- 分类导航 -->
    <scroll-view class="category-scroll" scroll-x>
      <view class="category-list">
        <view 
          v-for="(category, index) in categories" 
          :key="index"
          :class="['category-item', currentCategory === category.PassageCategoryName ? 'active' : '']"
          @tap="switchCategory(category.PassageCategoryName)"
        >
          {{ category.PassageCategoryName }}
        </view>
      </view>
    </scroll-view>

    <!-- 网站列表 -->
    <scroll-view 
      class="website-list" 
      scroll-y
    >
      <!-- 网站卡片列表 -->
      <view class="website-grid">
        <view 
          class="website-card"
          v-for="(site, index) in filteredWebsites"
          :key="index"
          @tap="openWebsite(site.url)"
          :style="{ animationDelay: index * 0.05 + 's' }"
        >
          <!-- 网站图标和名称 -->
          <view class="card-header">
            <image 
              :src="api.BASE_URL + site.icon || '/static/icons/default.png'" 
              class="website-icon"
              mode="aspectFill"
            ></image>
            <text class="website-name text-ellipsis">{{ site.name }}</text>
          </view>
          
          <!-- 网站描述 -->
          <text class="website-desc text-ellipsis-2">{{ site.description }}</text>
          
          <!-- 底部操作栏 -->
          <view class="card-footer">
            <text class="website-time">{{ formatTime(site.create_time) }}</text>
            <view class="actions">
              <button 
                class="action-btn"
                @tap.stop="copyUrl(site.url)"
              >
                <uni-icons type="link" size="14" color="#666"></uni-icons>
              </button>
            </view>
          </view>
        </view>
      </view>

      <!-- 无数据提示 -->
      <view class="empty-state" v-if="filteredWebsites.length === 0">
        <image src="/static/empty.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">{{ searchKey ? '未找到相关网站' : '暂无网站数据' }}</text>
      </view>
    </scroll-view>

    <!-- 分享菜单 -->
    <uni-popup ref="sharePopup" type="bottom">
      <view class="share-menu">
        <view class="share-title">分享到</view>
        <view class="share-options">
          <button class="share-option" open-type="share">
            <uni-icons type="weixin" size="32" color="#07c160"></uni-icons>
            <text>微信</text>
          </button>
          <button class="share-option" @tap="copyShareLink">
            <uni-icons type="link" size="32" color="#666"></uni-icons>
            <text>复制链接</text>
          </button>
        </view>
        <button class="cancel-share" @tap="closeShare">取消</button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { api } from '@/utils/request'

// 响应式状态
const searchKey = ref('')
const currentCategory = ref('')
const categories = ref([])
const expandedSites = ref([])

// 分享相关
const sharePopup = ref(null)
const currentShareSite = ref(null)

// 计算属性
const filteredWebsites = computed(() => {
  if (!categories.value.length) return []
  
  if (!currentCategory.value && categories.value.length > 0) {
    currentCategory.value = categories.value[0].PassageCategoryName
  }
  
  const currentCategoryData = categories.value.find(
    category => category.PassageCategoryName === currentCategory.value
  )
  
  let sites = currentCategoryData?.items || []

  if (searchKey.value) {
    sites = sites.filter(site => 
      site.name.toLowerCase().includes(searchKey.value.toLowerCase()) ||
      site.description.toLowerCase().includes(searchKey.value.toLowerCase())
    )
  }

  return sites
})

// 方法
const getPassageData = async () => {
  try {
    const res = await api.request({
      url: '/api/passage/get_passage/',
      method: 'GET'
    })
    
    if (res.code === 200) {
      categories.value = res.data
      // 默认选中第一个分类
      if(res.data.length > 0) {
        currentCategory.value = res.data[0].PassageCategoryName
      }
    }
  } catch (error) {
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    })
  }
}

// 切换分类
const switchCategory = (categoryName) => {
  currentCategory.value = categoryName
}

// 打开网站
const openWebsite = (url) => {
  uni.navigateTo({
    url: `/pages/passage/webview?url=${encodeURIComponent(url)}`
  })
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 展开/收起描述
const toggleExpand = (siteId) => {
  const index = expandedSites.value.indexOf(siteId)
  if(index > -1) {
    expandedSites.value.splice(index, 1)
  } else {
    expandedSites.value.push(siteId)
  }
}

// 搜索处理
const handleSearch = () => {
  // 可以添加搜索逻辑
  console.log('搜索:', searchKey.value)
}

// 清除搜索
const clearSearch = () => {
  searchKey.value = ''
}

// 分享网站
const shareWebsite = (site) => {
  currentShareSite.value = site
  sharePopup.value.open()
}

// 关闭分享菜单
const closeShare = () => {
  sharePopup.value.close()
}

// 复制链接
const copyUrl = (url) => {
  uni.setClipboardData({
    data: url,
    success: () => {
      uni.showToast({
        title: '链接已复制',
        icon: 'success'
      })
    }
  })
}

// 复制分享链接
const copyShareLink = () => {
  if(!currentShareSite.value) return
  
  const shareLink = `${currentShareSite.value.name}: ${currentShareSite.value.url}`
  uni.setClipboardData({
    data: shareLink,
    success: () => {
      uni.showToast({
        title: '分享链接已复制',
        icon: 'success'
      })
      closeShare()
    }
  })
}

onMounted(() => {
  getPassageData()
})
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding: 20rpx;
}

.search-bar {
  margin-bottom: 20rpx;
  
  .search-box {
    position: relative;
    display: flex;
    align-items: center;
    background: #fff;
    height: 80rpx;
    border-radius: 40rpx;
    padding: 0 30rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
    
    .icon-segi-icon-search {
      font-size: 32rpx;
      color: #999;
      margin-right: 10rpx;
    }
    
    input {
      flex: 1;
      height: 100%;
      font-size: 28rpx;
      color: #333;
    }
    
    .clear-btn {
      padding: 10rpx;
      font-size: 32rpx;
      color: #999;
      
      &:active {
        opacity: 0.7;
      }
    }
  }
}

.category-scroll {
  margin-bottom: 20rpx;
  
  .category-list {
    display: flex;
    padding: 10rpx 0;
    
    .category-item {
      padding: 12rpx 30rpx;
      margin-right: 20rpx;
      background: #fff;
      border-radius: 30rpx;
      font-size: 28rpx;
      color: #666;
      white-space: nowrap;
      transition: all 0.3s;
      box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
      
      &.active {
        background: #007AFF;
        color: #fff;
      }
      
      &:active {
        transform: scale(0.95);
        opacity: 0.8;
      }
    }
  }
}

.website-list {
  height: calc(100vh - 240rpx);
  padding-bottom: 40rpx;
}

.website-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320rpx, 1fr));
  gap: 20rpx;
  padding: 10rpx;
  
  // 确保在小屏幕上至少显示2列
  @media screen and (max-width: 768rpx) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.website-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
  display: flex;
  flex-direction: column;
  animation: slideIn 0.3s ease-out both;
  height: 240rpx; // 固定卡片高度
  
  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;
    
    .website-icon {
      width: 64rpx;
      height: 64rpx;
      border-radius: 12rpx;
      margin-right: 12rpx;
      flex-shrink: 0;
    }
    
    .website-name {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }
  }
  
  .website-desc {
    font-size: 24rpx;
    color: #666;
    line-height: 1.4;
    flex: 1;
    margin-bottom: 16rpx;
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .website-time {
      font-size: 22rpx;
      color: #999;
    }
    
    .actions {
      display: flex;
      gap: 12rpx;
      
      .action-btn {
        padding: 0;
        width: 48rpx;
        height: 48rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f8f8f8;
        border-radius: 24rpx;
        
        &:active {
          opacity: 0.7;
        }
      }
    }
  }
  
  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
}

.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.share-menu {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 30rpx;
  
  .share-title {
    text-align: center;
    font-size: 32rpx;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .share-options {
    display: flex;
    justify-content: space-around;
    margin-bottom: 30rpx;
    
    .share-option {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 12rpx;
      background: none;
      padding: 0;
      
      text {
        font-size: 24rpx;
        color: #666;
      }
      
      &:active {
        opacity: 0.7;
      }
    }
  }
  
  .cancel-share {
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    font-size: 32rpx;
    color: #666;
    background: #f5f5f5;
    border-radius: 45rpx;
    
    &:active {
      opacity: 0.7;
    }
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 文本省略样式
.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.text-ellipsis-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
</style>
